<template>
  <div class="app-container">
    <SearchFilter
      size="medium"
      :maxShow="3"
      @search="handleQuery"
      @reset="resetQuery"
    >
      <el-form
        :model="queryParams"
        label-position="right"
        label-width="90px"
        ref="queryForm"
      >
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="用户组名称" prop="groupName">
              <el-input
                v-model="queryParams.groupName"
                placeholder="请输入用户组名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </SearchFilter>

    <div class="content-container">
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="1.5">
          <p class="header-title">用户组列表</p>
        </el-col>
        <div>
          <el-col :span="1.5" v-if="ids.length">
            <el-button
              size="small"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['work:repair:remove']"
              >批量删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd"
              v-hasPermi="['work:repair:add']"
              >新增用户组</el-button
            >
          </el-col>
        </div>
      </el-row>

      <el-table
        v-loading="loading"
        :data="groupList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column label="用户组名称" align="center" prop="groupName" />
        <el-table-column label="组成员" align="center" prop="userStrs" />
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="220"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              class="text-text table-btn"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              class="text-danger table-btn"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      custom-class="dialog"
      :visible.sync="open"
      append-to-body
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-position="top"
        label-width="80px"
      >
        <el-row type="flex" justify="space-between">
          <el-col>
            <el-form-item label="用户组名称" prop="groupName">
              <el-input
                v-model="form.groupName"
                placeholder="请输入用户组名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="维修人员" prop="userIds">
              <el-select
                clearable
                v-model="form.userIds"
                placeholder="请选择维修人员"
                multiple
                @change="selectChange"
              >
                <el-option
                  v-for="item in repairOptions"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.userName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                rows="5"
                v-model="form.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList } from "@/api/menu";
import SearchFilter from "@/components/SearchFile";

import {
  addGroup,
  getGroupPage,
  getGroupInfo,
  updateGroup,
  deleteGroup,
} from "@/api";

export default {
  name: "Repair",
  components: { SearchFilter },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 维修人员列表
      repairOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
      },
      // 总条数
      total: 0,
      groupList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        equipmentId: [
          { required: true, message: "设备名称不能为空", trigger: "blur" },
        ],
        endDate: [
          { required: true, message: "截止时间不能为空", trigger: "blur" },
        ],
        repairPerson: [
          { required: true, message: "维修人员不能为空", trigger: "blur" },
        ],
        repairUser: [
          { required: true, message: "报修联系人不能为空", trigger: "blur" },
        ],
        repairPhone: [
          {
            required: true,
            message: "报修人联系方式不能为空",
            trigger: "blur",
          },
          {
            pattern: /(1[34578]\d{9})$/,
            message: "请填写正确的手机号码",
            trigger: "change",
          },
        ],
      },
      // 选中数组
      ids: [],
    };
  },
  created() {
    this.getUserListHandle();
    this.getList();
  },
  methods: {
    async getUserListHandle() {
      const deptCode = this.$store.state.user.user.dept.deptCode;
      const roleKey = deptCode.substring(deptCode.length - 4);

      const repairRes = await getUserList({ roleKey: roleKey + "-repair" });
      if (repairRes.data.length) {
        this.repairOptions = repairRes.data.map((item) => {
          return { ...item, userId: item.userId + "" };
        });
      }
    },

    selectChange(val) {
      console.log(val);
      // this.form = {};
    },

    getList() {
      this.loading = true;
      getGroupPage({
        ...this.queryParams,
      }).then((res) => {
        console.log(res);
        this.groupList = res.rows;
        // this.groupList.map((item) => {
        //   const arr = [];
        //   item.users.map((i) => {
        //     arr.push(i.nickName);
        //   });
        //   item.groupUsers = arr.toString();
        // });
        this.total = res.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        groupName: null,
        userIds: [],
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.groupId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row);
      this.reset();
      const id = row.groupId;
      getGroupInfo(id).then((res) => {
        this.form = res.data;

        this.form.userIds = [];
        if (res.data.userIdStrs) {
          this.form.userIds = res.data.userIdStrs.split(",");
        }

        this.open = true;
        this.title = "修改用户组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        console.log(this.form);
        if (valid) {
          console.log(this.form);
          if (this.form.groupId != null) {
            updateGroup({
              ...this.form,
            }).then((res) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGroup({
              ...this.form,
            }).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(this.ids);
      const groupIds = row.groupId || this.ids;
      this.$modal
        .confirm("是否确认删除该分组？")
        .then(function () {
          return deleteGroup(groupIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
